﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Jzy.BLL.DocManger;
using System.Collections.Generic;
using Jzy.Model.DocManger;
using Jzy.Core.Common;

using Jzy.Core.Common.Web;
using Frame.Lib.Common;
using Frame.Lib.Web;
using Frame.Lib.Core.Right;
using Frame.Lib.Enums;
using Frame.Lib.Utilities;
using Jzy.DAL;


public partial class DocManger_List : PageList
{
    private int dirID;
    private DirBO dir = new DirBO();
    private DocumentBO doc = new DocumentBO();
    private string strSelectDirIDs;//选中的目录ＩＤ
    private string strSelectDocIDs;//选中的文档ＩＤ
    private List<int> lstDirEditIDs;//当前用户可拥有编辑权限的ID集合   
    private PagerSortSetting _setting;
    private ListMode DocListMode
    {
        get
        {
            if (AppSession.Session["DocListMode"] == null)
            {
                AppSession.Session["DocListMode"] = ListMode.DirDoc;
            }
            return (ListMode)AppSession.Session["DocListMode"];
        }
        set
        {
            AppSession.Session["DocListMode"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        _setting = this.Footer1.InitPager(new BindViewHandler(BindView));

        dirID = int.Parse(Request["DirID"]);

        hidMyDirIDs.Value = ",";
        hidMyDocIDs.Value = ",";

        //获取目录编辑权限的集合
        RecordRightBO right = new RecordRightBO(OTableName.DocDirRight);
        lstDirEditIDs = right.GetBindIDs(AppSession.UserID, RecordRightName.Edit, RightOwnerType.User);


        if (!IsPostBack)
        {
            if (DocListMode == ListMode.DirDoc)
            {
                btnDisplay.Text = "隐藏目录";
            }
            else
            {
                btnDisplay.Text = "显示目录";
            }
            Pager.BindDrp(drpPager);
            BindView();
            if (dirID != 0)
            {
                lblDir.Text = dir.GetName(dirID);
            }
            else
            {
                lblDir.Text = "<b>已是顶级目录</b>";
                btnUpper.Enabled = false;
            }
        }
        AddAttr();
        strSelectDirIDs = hidSelectDirIDs.Value;
        hidSelectDirIDs.Value = "";
        strSelectDocIDs = hidSelectDocIDs.Value;
        hidSelectDocIDs.Value = "";
    }

    private void AddAttr()
    {
        JSUtil.ClickBtn(lnkDelete, btnDelete);

        btnDelete.Attributes.Add("onclick", "return delDirDoc(" + hidSelectDirIDs.ClientID + "," + hidSelectDocIDs.ClientID + ",'确认删除所选目录和文档？');");

        JSUtil.ClickBtn(lnkUpper, btnUpper);


        lnkMove.Attributes.Add("onclick", "moveDoc('MoveDlg.aspx',document.all." + hidSelectDirIDs.ClientID + ",document.all." + hidSelectDocIDs.ClientID + ",document.all." + hidMyDirIDs.ClientID + ",document.all." + hidMyDocIDs.ClientID + ",document.all." + btnRefresh.ClientID + ")");

        string strUrl = "DirEdit.aspx?UpperID=" + dirID;

        if (dirID == 0)//最上级目录
        {
            liAdd.Visible = false;
            liDelete.Visible = false;
            btnDisplay.Visible = false;
        }
        else
        {
            //判断当前用户有没有上级目录的增加权限
            DirInfo info = dir.GetInfo(dirID);
            int userID = AppSession.UserID;

            bool flag = false;
            if (userID == Constants.ADMIN_ID)//是管理员
            {
                flag = true;
            }
            else
            {
                int creatorID = (int)info.CreatorID;
                if (creatorID == userID)//创建者
                {
                    flag = true;
                }
                else
                {
                    RecordRightBO right = new RecordRightBO(OTableName.DocDirRight);
                    flag = right.HaveRight(dirID, userID, RecordRightName.Add, RightOwnerType.User);
                }

            }
            if (flag)
            {
                JSUtil.ShowForm(lnkAddDir, "增加目录", null, GlobalVar.WebCurrPath + strUrl, 250, 201);
                lnkAddDir.Attributes["onclick"] += ";HideDiv(true);";
                lnkAddDoc.Attributes.Add("onclick", "navigate('DocEdit.aspx?DirID=" + dirID + "')");
                lnkAddDoc.NavigateUrl = "DocEdit.aspx?DirID=" + dirID ;
            }
            else
            {
                lnkAddDoc.Visible = false;
                lnkAddDir.Visible = false;
            }
        }
    }

    private void BindView()
    {
        GVUtil.InitGV(gvList);
        Pager.SetPageSize(_setting, drpPager);
        int userID = AppSession.UserID;

        DataTable dt = doc.GetDocDirList(dirID, userID, DocListMode);

        gvList.DataSource = _setting.GetDataView(dt);
        gvList.DataKeyNames = new string[] { "ID" };
        gvList.DataBind();
    }

    protected string BindType(int type)
    {
        string strTypeUrl = GlobalVar.WebAppPath + "common/images/common/";
        switch (type)
        {
            case 0:
                strTypeUrl += "vbook.gif";
                break;
            case 1:
                strTypeUrl += "folder.gif";
                break;
        }
        return strTypeUrl;
    }

    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        BindView();
    }

    protected void btnDisplay_Click(object sender, EventArgs e)
    {
        if (btnDisplay.Text == "显示目录")
        {
            DocListMode = ListMode.DirDoc;
            btnDisplay.Text = "隐藏目录";
            BindView();
        }
        else
        {
            DocListMode = ListMode.Doc;
            btnDisplay.Text = "显示目录";
            BindView();
        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        int userID = AppSession.UserID;

        if (strSelectDirIDs != "")
        {
            List<int> lstSelectIDs = GetSelectIDs(strSelectDirIDs);
            List<int> lstDisableDeleteIDs = new List<int>();
            string strScript = "";
            if (userID != Constants.ADMIN_ID)//管理员不用判断权限
            {
                RecordRightBO right = new RecordRightBO(OTableName.DocDirRight);
                List<int> lstBindIDs = right.GetBindIDs(userID, RecordRightName.Delete, RightOwnerType.User);//当前用户拥有删除权限的目录集合

                Dictionary<int, int> ditCreatorIDs = dir.GetCreatorIDs(lstSelectIDs);
                for (int i = 0; i < lstSelectIDs.Count; i++)
                {
                    int selectID = lstSelectIDs[i];
                    if (ditCreatorIDs.ContainsKey(selectID))//用于判断字典中是否存在些键，有可能当你删除时，别人已把些目录删除了，这样就会导至异常
                    {
                        if (ditCreatorIDs[selectID] == userID)//判断是否是创建者
                        {
                            continue;
                        }
                    }
                    if (lstBindIDs.IndexOf(selectID) < 0)
                    {
                        lstDisableDeleteIDs.Add(lstSelectIDs[i]);
                        lstSelectIDs.RemoveAt(i);
                        i--;
                    }
                }

                if (lstDisableDeleteIDs.Count > 0)//如果删除没有权限的目录，则进行提示哪些目录没有权限
                {
                    List<string> lstDisableDeleteNames = dir.GetName(lstDisableDeleteIDs);
                    string strDisableDeleteNames = "“" + StrUtil.MergeToStr(lstDisableDeleteNames, "”，“") + "” ";
                    strScript += "alert('" + strDisableDeleteNames + "目录您没权限删除！');";
                }
            }
            if (lstSelectIDs.Count > 0)
            {
                dir.Delete(lstSelectIDs);
                strScript += "top.frames[0].document.getElementById('ctl00_ContentPlaceHolder1_btnRefresh').click();";//刷新左边的树
            }
            JSUtil.ExcuteJS(strScript);
        }
        if (strSelectDocIDs != "")
        {
            List<int> lstSelectIDs = GetSelectIDs(strSelectDocIDs);
            List<int> lstDisableDeleteIDs = new List<int>();

            if (userID != Constants.ADMIN_ID)//管理员不用判断权限
            {
                RecordRightBO right = new RecordRightBO(OTableName.DocRight);
                List<int> lstBindIDs = right.GetBindIDs(AppSession.UserID, RecordRightName.Delete, RightOwnerType.User);

                Dictionary<int, int> ditCreatorIDs = doc.GetCreatorIDs(lstSelectIDs);
                for (int i = 0; i < lstSelectIDs.Count; i++)
                {
                    int selectID = lstSelectIDs[i];
                    if (ditCreatorIDs.ContainsKey(selectID))
                    {
                        if (ditCreatorIDs[selectID] == AppSession.UserID)
                        {
                            continue;
                        }
                    }
                    if (lstBindIDs.IndexOf(selectID) < 0)
                    {
                        lstDisableDeleteIDs.Add(selectID);
                        lstSelectIDs.RemoveAt(i);
                        i--;
                    }
                }
                if (lstDisableDeleteIDs.Count > 0)
                {
                    List<string> lstDisableDeleteNames = doc.GetName(lstDisableDeleteIDs);
                    string strDisableDeleteNames = "“" + StrUtil.MergeToStr(lstDisableDeleteNames, "”，“") + "”";
                    string strScript = "alert('" + strDisableDeleteNames + "文档您没权限删除！');";
                    JSUtil.ExcuteJS(strScript);
                }
            }
            if (lstSelectIDs.Count > 0)
            {
                doc.Delete(lstSelectIDs);
            }
        }
        BindView();
    }
    private List<int> GetSelectIDs(string strSelectIDs)
    {
        int length = strSelectIDs.Length;
        strSelectIDs = strSelectIDs.Substring(1, length - 2);//去掉首尾逗号
        string[] strIDs = strSelectIDs.Split(',');
        List<int> lstSelectIDs = new List<int>(strIDs.Length);
        foreach (string str in strIDs)
        {
            if (str != "")
            {
                lstSelectIDs.Add(int.Parse(str));
            }
        }
        return lstSelectIDs;
    }
    protected void btnUpper_Click(object sender, EventArgs e)
    {
        DirInfo info = dir.GetInfo(dirID);
        Response.Redirect("List.aspx?DirID=" + info.UpperID, true);
    }
    protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string strID = gvList.DataKeys[e.Row.RowIndex]["ID"].ToString();

            CheckBox chkSelect = (CheckBox)e.Row.FindControl("chkSelect");
            HiddenField hidType = (HiddenField)e.Row.FindControl("hidType");
            int creatorID = int.Parse(((HiddenField)e.Row.FindControl("hidCreatorID")).Value);

            HyperLink lnkSetRight = (HyperLink)e.Row.FindControl("lnkSetRight");
            lnkSetRight.Style.Add("cursor", "pointer");
            lnkSetRight.Enabled = false;
            if (hidType.Value == "1")
            {
                chkSelect.Attributes.Add("onclick", "SetSelectID('" + hidSelectDirIDs.ClientID + "'," + strID + ")");
                string strUrl = "DirEdit.aspx?DirID=" + strID + "&RefreshButton=" + btnRefresh.ClientID;
                HyperLink lnkName = (HyperLink)e.Row.FindControl("lnkName");
                lnkName.Style.Add("cursor", "pointer");
                int id = int.Parse(strID);
                if (lstDirEditIDs.IndexOf(id) > -1 || creatorID == AppSession.UserID || Constants.ADMIN_ID == AppSession.UserID)
                {
                    JSUtil.ShowForm(lnkName, "修改目录", null, GlobalVar.WebCurrPath + strUrl, 280, 201);
                }
                else
                {
                    lnkName.Attributes.Add("onclick", "alert('对不起，您没有编辑该目录的权限！')");
                }


                if (creatorID == AppSession.UserID || Constants.ADMIN_ID == AppSession.UserID)
                {
                    hidMyDirIDs.Value += strID + ",";

                    //设置目录权限
                    strUrl = "SaveDirRight.aspx?DirID=" + strID;
                    lnkSetRight.Enabled = true;

                    JSUtil.ShowForm(lnkSetRight, "设置权限", null, strUrl, 300, 319);
                }
            }
            else
            {
                chkSelect.Attributes.Add("onclick", "SetSelectID('" + hidSelectDocIDs.ClientID + "'," + strID + ")");
                string strUrl = "DocDetail.aspx?DocID=" + strID;
                HyperLink lnkName = (HyperLink)e.Row.FindControl("lnkName");
                lnkName.NavigateUrl = strUrl;
                if (creatorID == AppSession.UserID || Constants.ADMIN_ID == AppSession.UserID)
                {
                    hidMyDocIDs.Value += strID + ",";

                    //设置文档权限
                    strUrl = "SaveDocRight.aspx?DocID=" + strID;
                    lnkSetRight.Enabled = true;

                    JSUtil.ShowForm(lnkSetRight, "设置权限", null, strUrl, 300, 319);
                }
            }
        }
        else if (e.Row.RowType == DataControlRowType.Header)
        {
            CheckBox chkSelectAll = (CheckBox)e.Row.FindControl("chkSelectAll");
            chkSelectAll.Attributes.Add("onclick", "SelectAll(" + gvList.ClientID + ")");
        }
    }
    protected void drpPager_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindView();
    }
    
}
